import {defineStore} from 'pinia'
import {ref,computed} from 'vue'
import {loginByPasswordAPI} from "@/apis/login.js";

export const useUserStore = defineStore('user', () => {

    const userInfo = ref({})
    const myShop=ref({})
    const orderList=ref([])
    const cart=ref([])
    const favorites=ref([])
    const isLogin=ref(false)

    //更新当前登录信息
    const updateUserInfo  = async ({account, password}) => {
        const res = await loginByPasswordAPI({account, password})
        //console.log('更新用户数据成功',res.data)
        userInfo.value = res.data
        isLogin.value=true
    }
    //修改当前登录信息
    const alterUserInfo =(newUserInfo)=>{
        userInfo.value=newUserInfo
        isLogin.value=true
    }
    //清除当前登录信息
    const clearUserInfo=()=>{
        userInfo.value={}
        myShop.value={}
        orderList.value=[]
        cart.value=[]
        favorites.value=[]
        isLogin.value=false
    }
    //获取当前登录状态
    // const isLogin= computed(()=>{
    //    return userInfo.value
    // })
    //获取当前头像
    const getAvatar=computed(()=>{
        return userInfo.value.avatar
    })


    const getCart=()=>{
        return cart
    }

    const clearCart=()=>{
        cart.value=[]
    }


    //实名认证
    const authRealName=({realName,identityNum})=>{
        userInfo.value.realname=realName
        userInfo.value.identityNum=identityNum
    }
    //是否实名
    const isAuth=computed(()=>{
        return userInfo.value.realname&&userInfo.value.identityNum
    })

    //绑定手机
    const bindPhoneNumber=(phoneNumber)=>{
        userInfo.value.phone=phoneNumber
    }

    const isBinging=computed(()=>{
        return userInfo.value.phone
    })

    //更改昵称
    const alterNickName=(nickName)=>{
        userInfo.value.username=nickName
    }

    const loadShop=(shop)=>{
        myShop.value=shop
    }

    const loadOrderList=(order)=>{
        orderList.value=order
    }
    
    // 获取用户角色
    const userRole = computed(() => {
        return userInfo.value.role || '';
    });
    
    // 是否为管理员
    const isAdmin = computed(() => {
        return userInfo.value.role === 'admin';
    });
    
    return {
        userInfo,
        myShop,
        orderList,
        cart,
        favorites,
        updateUserInfo,
        alterUserInfo,
        clearUserInfo,
        isLogin,
        getAvatar,
        authRealName,
        isAuth,
        bindPhoneNumber,
        isBinging,
        alterNickName,
        loadShop,
        loadOrderList,
        getCart,
        clearCart,
        userRole,
        isAdmin
    }
}, {
    //持久化存储
    persist: true,
})